// https://www.lintcode.com/problem/remove-duplicates-from-sorted-list-ii/

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: head is the head of the linked list
     * @return: head of the linked list
     */
    public ListNode deleteDuplicates(ListNode head) {
        // write your code here
        ListNode newHead = null;
        ListNode newTail = null;
        ListNode oldHead = head;
        while (oldHead != null) {
            ListNode nextNode = oldHead.next;
            if ((nextNode == null) || (nextNode.val != oldHead.val)) {
                if (newHead == null) {
                    newHead = oldHead;
                } else {
                    newTail.next = oldHead;
                }
                newTail = oldHead;
                newTail.next = null;
                oldHead = nextNode;
            } else {
                while ((nextNode != null) && (nextNode.val == oldHead.val)) {
                    nextNode = nextNode.next;
                }
                oldHead = nextNode;
            }
        }
        return newHead;
    }
}